package com.freemalll.merchant.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.freemalll.common.core.exception.BusinessException;
import com.freemalll.merchant.common.CommonEnum;
import com.freemalll.merchant.common.convert.MerchantReportDataConverter;
import com.freemalll.merchant.domain.dto.*;
import com.freemalll.merchant.domain.dto.merchantReport.MerchantAccountEditDto;
import com.freemalll.merchant.domain.dto.merchantReport.MerchantRateEditDto;
import com.freemalll.merchant.domain.dto.merchantReport.MerchantReportPageDto;
import com.freemalll.merchant.domain.entity.*;
import com.freemalll.merchant.domain.vo.merchantParameters.MerParamsDetailVO;
import com.freemalll.merchant.domain.vo.merchantReport.*;
import com.freemalll.merchant.mapper.MerchantReportMapper;
import com.freemalll.merchant.service.*;
import com.freemalll.merchant.service.merchantAuditManage.MerMerchantAuditEditLogService;
import com.freemalll.merchant.utils.AliOSSUtil;
import com.freemalll.merchant.utils.BeanUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class MerchantReportServiceImpl implements MerchantReportService {

    @Resource
    private MerchantReportMapper merchantReportMapper;
    @Resource
    private MerLicenseService merLicenseService;
    @Resource
    private MerAttachService merAttachService;
    @Resource
    private MerAttachValueService merAttachValueService;
    @Resource
    private MerRunInfoService merRunInfoService;
    @Resource
    private MerBankCardService merBankCardService;
    @Resource
    private MerMerchantCapitalOrderService merMerchantCapitalOrderService;
    @Resource
    private MerMerchantRateManageService merMerchantRateManageService;
    @Resource
    private MerMerchantAuditEditLogService merMerchantAuditEditLogService;
    @Resource
    private MerchantBusinessService merchantBusinessService;
    @Resource
    private MerMerchantRateManageDetailService merMerchantRateManageDetailService;
    @Resource
    private MerMerchantFormerNameService merMerchantFormerNameService;
    @Resource
    private AliOSSUtil aliOSSUtil;
    @Resource
    private MerParamsService merParamsService;
    @Resource
    private MerMerchantService merMerchantService;

    @Override
    public Page<MerchantReportPageVo> page(MerchantReportPageDto dto) {
        Page<MerchantReportPageVo> page = merchantReportMapper.page(dto.page(), dto);
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return page;
        }
        List<MerchantReportPageVo> records = page.getRecords();
        //场景分类转码
        MerParamsDetailVO sceneCategory = merParamsService.cacheDetail("scene_category");
        if (Objects.isNull(sceneCategory) || sceneCategory.getParamsDetailList().isEmpty()) {
            return page;
        }
        //处理场景分类
        for (MerchantReportPageVo vo : records) {
            if (StringUtils.hasText(vo.getSceneCategory())) {
                String paramNameByPrefix = merParamsService.findParamNameByPrefix(vo.getSceneCategory(), sceneCategory.getParamsDetailList());
                vo.setSceneCategory(paramNameByPrefix);
            }
        }
        return page;
    }

    @Override
    public MerchantReportVo getMerchantBasicInfo(String merId) {
        if (!StringUtils.hasText(merId)) {
            throw BusinessException.businessParamsNotExist("商户id不能为空");
        }
        //基础信息
        MerchantReportVo vo = merchantReportMapper.selectByMerId(merId);
        if (Objects.isNull(vo)) {
            throw BusinessException.businessParamsNotExist("商户信息不存在");
        }
        if (StringUtils.hasText(vo.getMerLogo())) {
            vo.setMerLogo(aliOSSUtil.getFileUrl(vo.getMerLogo()));
        }
        //场景类别，门店类型，品牌名称，合作政策转码
        vo.setSceneCategoryName(merParamsService.translateParamKeys(vo.getSceneCategory()));
        String auditPolicy = merParamsService.translateParamKeys(vo.getAuditPolicy());
        MerMerchant merchant = merMerchantService.getById(merId);
        auditPolicy = auditPolicy + "," + merchant.getMerLevel() + "," + merchant.getMerchantCreditLimit();
        vo.setAuditPolicy(auditPolicy);
        // 码值表设置申请类型名称
        vo.setApplyTypeName(
                Optional.ofNullable(vo.getApplyType())
                        .map(CommonEnum.applyType::getApplyTypeByCode)
                        .map(CommonEnum.applyType::getDescription)
                        .orElse(vo.getApplyType())
        );
        // 码值表设置店铺类型名称
        vo.setStoreType(
                Optional.ofNullable(vo.getStoreType())
                        .map(CommonEnum.storeType::getStoreTypeByCode)
                        .map(CommonEnum.storeType::getDescription)
                        .orElse(vo.getStoreType())
        );

        // 码值表设置品牌类型名称
        vo.setBrandType(
                Optional.ofNullable(vo.getBrandType())
                        .map(CommonEnum.brandType::getBrandTypeByCode)
                        .map(CommonEnum.brandType::getDescription)
                        .orElse(vo.getBrandType())
        );
        //商户曾用名
        List<MerMerchantFormerName> formerNames = merMerchantFormerNameService.list(Wrappers.<MerMerchantFormerName>lambdaQuery().eq(MerMerchantFormerName::getMerId, merId));
        List<String> filterNames = formerNames.stream().map(MerMerchantFormerName::getFormerName).collect(Collectors.toList());
        vo.setMerchantSFormerNameList(filterNames);

        //工商证照
        BusinessLicenseDto merLicenseInfo = getMerLicenseInfo(merId);
        //获取附件
        String url = merAttachService.selectAttachByMerIdAndConfigCode(merId, CommonEnum.businessPhotoType.business_license.name());
        merLicenseInfo.setLicenseImage(aliOSSUtil.getFileUrl(url));
        vo.setBusinessInfo(merLicenseInfo);
        //商户经营信息
        MerBusinessInfoDto merBusinessInfo = getMerBusinessInfo(merId);
        vo.setMerBusinessInfo(merBusinessInfo);
        //经营附件 附件类型(1,初审附件,2,企业征信附件,3,经营附件)
        List<MerAttachDto> list = merAttachService.queryAttachListByOperate(merId, 3);
        for (MerAttachDto merAttach : list) {
            List<MerAttachValue> attachValues = merAttachValueService.list(Wrappers.<MerAttachValue>lambdaQuery().eq(MerAttachValue::getAttachId, merAttach.getAttachId()));
            List<String> attachResultList = new ArrayList<>();
            for (MerAttachValue attachValue : attachValues) {
                String fileUrl = aliOSSUtil.getFileUrl(attachValue.getValValue());
                attachResultList.add(fileUrl);
            }
            merAttach.setAttachResultList(attachResultList);
        }
        vo.setMerAttachList(list);
        return vo;
    }

    @Override
    public MerchantBusinessParametersVo getMerchantBusinessParameters(String merId) {
        MerchantBusinessParametersVo vo = new MerchantBusinessParametersVo();
        //收款户信息
        List<MerBackCardDto> backCardDtoList = merBankCardService.listByMerId(merId);
        vo.setBackCardDto(backCardDtoList);
        //资方顺位
        List<MerMerchantCapitalOrderDto> capitalOrderDtoList = merMerchantCapitalOrderService.listByMerId(merId);
        vo.setCapitalOrderDto(capitalOrderDtoList);
        MerMerchant merchant = merMerchantService.getById(merId);
        //费率
        List<MerchantRateDto> rateDtoList = merMerchantRateManageService.listByMerId(merId, merchant.getSceneParentCategory());
        vo.setSourceInfoDto(rateDtoList);
        return vo;
    }

    @Override
    public MerchantPerformanceVo getMerchantPerformance(String merId, String tabType) {
        //业务表现  调用数仓的表
        MerchantPerformanceVo vo = new MerchantPerformanceVo();
        MerchantBizPerfVo businessPerformance = merchantBusinessService.getBusinessPerformance(merId);
        vo.setBusinessPerformance(businessPerformance);
        //业务表现月
        List<MerchantBizPerfMonthVo> businessPerformanceMonth = merchantBusinessService.getBusinessPerformanceMonth(merId, tabType);
        //处理数据格式
        List<MerchantBizPerfMonthConvertVo> merchantBizPerfMonthConvertVos = this.dealWithMonth(businessPerformanceMonth);
        vo.setBusinessPerformanceMonth(merchantBizPerfMonthConvertVos);
        return vo;
    }

    private List<MerchantBizPerfMonthConvertVo> dealWithMonth(List<MerchantBizPerfMonthVo> businessPerformanceMonth) {
        if (CollectionUtils.isEmpty(businessPerformanceMonth)) {
            return Collections.emptyList();
        }
        //处理list
        return MerchantReportDataConverter.convert(businessPerformanceMonth);
    }

    @Override
    public List<MerMerchantAuditEditLog> getChangeRecord(String merId, String changeType) {
        return merMerchantAuditEditLogService.list(Wrappers.<MerMerchantAuditEditLog>lambdaQuery()
                .eq(MerMerchantAuditEditLog::getMerId, merId)
                .eq(MerMerchantAuditEditLog::getModule, changeType)
                .orderByDesc(MerMerchantAuditEditLog::getAddTime));
    }

    @Override
    public void rateActivationStatus(MerchantRateEditDto dto) {
        if (dto.getType().equals("1")) {
            if (!StringUtils.hasText(dto.getMerId())) {
                throw BusinessException.businessParamsNotExist("商户id不能为空");
            }
            merMerchantRateManageService.update(Wrappers.<MerMerchantRateManage>lambdaUpdate()
                    .eq(MerMerchantRateManage::getMerId, dto.getMerId())
                    .eq(MerMerchantRateManage::getSourceId, dto.getId())
                    .set(MerMerchantRateManage::getEnableFlag, dto.getEnableFlag()));
        } else {
            merMerchantRateManageDetailService.update(Wrappers.<MerMerchantRateManageDetail>lambdaUpdate()
                    .eq(MerMerchantRateManageDetail::getRateDetailId, dto.getId())
                    .set(MerMerchantRateManageDetail::getEnableFlag, dto.getEnableFlag()));
        }
    }

    @Override
    public void accountEnableStatusEdit(MerchantAccountEditDto dto) {
        merBankCardService.update(Wrappers.<MerBankCard>lambdaUpdate()
                .eq(MerBankCard::getMerId, dto.getMerId())
                .eq(MerBankCard::getCardId, dto.getCardId())
                .set(MerBankCard::getCardStatus, dto.getCardStatus()));

    }

    private MerBusinessInfoDto getMerBusinessInfo(String merId) {
        MerBusinessInfoDto merBusinessInfo = new MerBusinessInfoDto();
        MerRunInfo merRunInfo = merRunInfoService.getOne(Wrappers.<MerRunInfo>lambdaQuery().eq(MerRunInfo::getMerId, merId));
        if (Objects.isNull(merRunInfo)) {
            return merBusinessInfo;
        }
        BeanUtils.copyPropertiesIgnoreNull(merRunInfo, merBusinessInfo);
        merBusinessInfo.setOnlinePlatformName(merParamsService.translateParamKeys(merBusinessInfo.getOnlinePlatform()));
        merBusinessInfo.setProjectListName(merParamsService.translateParamKeys(merBusinessInfo.getProjectList()));
        merBusinessInfo.setAdvertisementName(merParamsService.translateParamKeys(merBusinessInfo.getAdvertisement()));
        return merBusinessInfo;
    }

    /**
     * 获取商户工商证照信息
     *
     * @param merId 商户id
     * @return 商户工商信息
     */
    private BusinessLicenseDto getMerLicenseInfo(String merId) {
        BusinessLicenseDto businessLicenseDto = merLicenseService.getBusinessLicenseById(merId);
        //附件地址
        MerAttach attach = merAttachService.getOne(Wrappers.<MerAttach>lambdaQuery()
                .eq(MerAttach::getMerId, merId)
                .eq(MerAttach::getConfigCode, CommonEnum.businessPhotoType.business_license.name())
                .last(" limit 1 "));
        if (Objects.nonNull(attach)) {
            MerAttachValue attachValue = merAttachValueService.getOne(Wrappers.<MerAttachValue>lambdaQuery()
                    .eq(MerAttachValue::getAttachId, attach.getAttachId())
                    .orderByDesc(MerAttachValue::getAddTime)
                    .last(" limit 1 "));
            if (Objects.nonNull(attachValue)) {
                businessLicenseDto.setLicenseImage(attachValue.getValValue());
            }
        }
        return businessLicenseDto;
    }
}
